const { User } = require('../models/index')
 
const gather = {
  regist: (ws, data) => {
    return new Promise((resolve) => {
      User.create(data.data).then((result)=>{
        if(!result)return;
        if(result){
          console.log(result.dataValues)
          backdata = {type:"success",info:{res:data.info.req,msg:result.name+'注册成功'},data:{}}
          ws.send(JSON.stringify(backdata))
        }
      }).catch((error)=>{
        ws.send(JSON.stringify({type:"failed",info:{res:data.info.req,msg:'注册失败'},data:{}}))
        console.log(error)
      })   
    })
  },
  logon: (ws,data) => {
    return new Promise((resolve) => {
      User.findOne({where:data.data,raw:true}).then((result)=>{
        if(result){
          console.log(result)
          ws.send(JSON.stringify({type:"success",info:{res:data.info.req,msg:"登录成功"},data:{id:result.id,name:result.name,role:''}}))
          resolve(result.id)
        }
        else ws.send(JSON.stringify({type:"error",info:{res:data.info.req,msg:'登录失误'},data:{}}))
      }).catch((error)=>{
        ws.send(JSON.stringify({type:"failed",info:{res:data.info.req,msg:'登录失败'},data:{}}))
        console.log(error)
      })   
    })
  },
  test: (ws,data) => {  
    var interval = null
    re=JSON.stringify({type:"",info:{res:data.info.req,},data:{}});
      if(data.data=="test"){
        ws.send(re)
        interval = setInterval(()=>ws.send(re), 10000);
      }
      else    
      ws.send(re)
  },
  uid:0,
  common:(ws,req)=>{
    ws.send('{"type":0,"data":"Hello client!","info":""}')
    ws.on('message', function (reqdata) {    
      data = JSON.parse(reqdata)
      console.log(data.type)     
        switch(data.info.action){
          case "login":
            gather.logon(ws,data).then(res=>uid=res)
            break;
          case 'regist':
            gather.regist(ws,data)
            break;
          case 'test':
            gather.test(ws,data)
            break;
          default:
            ws.send(reqdata)
            console.log("There is no proper way")
        }
    })
    ws.on('close',function(){
      console.log('连接关闭')
    })
  }
}
module.exports = gather;